<template>
  <el-dialog
      v-model="visible"
      :close-on-click-modal="false"
      :show-close="true"
      :title="props.title || '面具选择'"
      :width="props.device === DeviceEnum.MOBILE ? '90%' : '60%'"
      class="mask-info-dialog"
      @close="props.closeDialog()"
  >
    <div class="dialog-content">
      <!-- 面具卡片区域 -->
      <div class="masks-container">
        <div v-if="maskList.length === 0 && !loading" class="empty-state">
          <el-icon class="empty-icon">
            <Box/>
          </el-icon>
          <p>暂无可用面具</p>
        </div>

        <div class="masks-grid">
          <div
              v-for="mask in maskList"
              :key="mask.id"
              class="mask-card"
              :class="{
                  'is-flipped': selectedMaskId === mask.id,
                  'is-selected': selectedMaskId === mask.id
              }"
              @click="selectMask(mask)"
          >
            <!-- 卡片正面 -->
            <div class="card-face card-front">
              <div class="card-content">
                <!-- 卡片样式               -->
                <div class="card-icon">
                  <svg-icon :icon-class="mask.icon || 'logo'" class-icon="logo" size="40"/>
                </div>
                <h3 class="mask-name">{{ mask.name }}</h3>
                <p class="mask-description">{{ mask.description || '暂无描述信息' }}</p>
                <div class="flip-hint">
                  <el-icon>
                    <Refresh/>
                  </el-icon>
                  <span>未选择 , 点击查看详情</span>
                </div>
              </div>
            </div>

            <!-- 卡片背面 -->
            <div class="card-face card-back">
              <div class="card-content">
                <div class="card-icon-large">
                  <svg-icon :icon-class="mask.icon || 'logo'" class-icon="logo" size="60"/>
                </div>
                <h3 class="mask-name">{{ mask.name }}</h3>
                <div class="prompt-container">
                  <div class="prompt-label">提示词:</div>
                  <el-scrollbar class="prompt-scrollbar">
                    <div class="mask-prompt">{{ mask.prompt || '暂无提示词' }}</div>
                  </el-scrollbar>
                </div>
                <div class="flip-hint">
                  <el-icon>
                    <Refresh/>
                  </el-icon>
                  <span>已选择 , 点击返回</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-if="loading" class="loading-state">
          <el-icon class="loading-icon">
            <Loading/>
          </el-icon>
          <span>加载中...</span>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="dialog-footer">
        <div style="flex:1;display:flex;justify-content:flex-start;">
          <el-button @click="deselectAll">清除选择</el-button>
        </div>
        <div style="display:flex;gap:12px;">
          <el-button @click="props.closeDialog()">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认选择</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import {ref, computed, onMounted, watch} from 'vue';
import {
  Box, Loading, Refresh
} from '@element-plus/icons-vue';
import {ElMessage} from 'element-plus';
import {DeviceEnum} from "@/enums/DeviceEnum";
import {
  UserChatConversationDetailVO,
  UserChatMaskVO
} from "@/api/ai/chat/user-chat/type";
import {UserChatAPI} from "@/api/ai/chat/user-chat";

defineOptions({
  name: "MaskInfoDialog",
  inheritAttrs: false,
});

const props = withDefaults(defineProps<{
  visible: boolean;
  title: string;
  device?: DeviceEnum;
  closeDialog: (callback?: () => void) => void;
  conversationId: string;
  currentConversationInfo?: UserChatConversationDetailVO
}>(), {
  currentConversationInfo: () => ({}) as UserChatConversationDetailVO,
  device: DeviceEnum.DESKTOP,
});

const emits = defineEmits<{
  (event: "update:visible", visible: boolean): void
  (event: "update:currentConversationInfo", info: UserChatConversationDetailVO): void
}>()

// hooks
const visible = useVModel(props, 'visible', emits)

// 数据
const maskList = ref<UserChatMaskVO[]>([]);
const loading = ref(false);
const selectedMaskId = ref<number | null>(null);

// 加载面具列表
async function loadMasks() {
  try {
    loading.value = true;
    const {data} = await UserChatAPI.MASK_LIST.request();
    maskList.value = data;
    selectedMaskId.value = props.currentConversationInfo?.maskInfo?.id || null;
  } catch (error) {
    console.error('加载面具失败:', error);
    ElMessage.error('加载面具失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 选择面具
function selectMask(mask: UserChatMaskVO) {
  if (!mask.id) return;

  if (selectedMaskId.value === mask.id) {
    // 如果点击已选中的面具，则取消选择
    selectedMaskId.value = null;
  } else {
    // 否则选择当前面具
    selectedMaskId.value = mask.id;
  }
}

// 清除所有选择
function deselectAll() {
  selectedMaskId.value = null;
}

// 确认选择
async function handleConfirm() {
  const selectedMask = maskList.value.find(mask => mask.id === selectedMaskId.value);

  // 更新当前对话信息
  const updatedInfo: UserChatConversationDetailVO = {
    ...props.currentConversationInfo,
    maskInfo: selectedMask ? {
      id: selectedMask.id,
      name: selectedMask.name,
      icon: selectedMask.icon
    } : {}
  };

  // 更新会话信息
  await UserChatAPI.BIND_MASK.request({
    conversationId: props.conversationId,
    maskId: selectedMask ? selectedMask.id : undefined
  });

  // 提示用户选择
  if (selectedMask) {
    ElMessage.success(`已带上面具: ${selectedMask.name}`);
  } else if (props.currentConversationInfo?.maskInfo?.id) {
    ElMessage.warning(`已摘下面具: ${props.currentConversationInfo.maskInfo.name}`);
  } else {
    ElMessage.info('未选择任何面具');
  }

  // 触发更新事件
  emits('update:currentConversationInfo', updatedInfo);
  props.closeDialog();
}

// 初始化加载数据
onMounted(() => {
  loadMasks();
});
</script>

<style lang="scss" scoped>
.mask-info-dialog {

  .dialog-content {
    display: flex;
    flex-direction: column;
    height: 70vh;

    .masks-container {
      flex: 1;
      overflow-y: auto;
      padding: 10px 10px;

      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 300px;
        color: var(--el-text-color-secondary);

        .empty-icon {
          font-size: 60px;
          margin-bottom: 20px;
          opacity: 0.5;
        }

        p {
          margin: 0;
          font-size: 16px;
        }
      }

      .masks-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 25px;
        padding: 10px;

        @media (max-width: 768px) {
          grid-template-columns: 1fr;
        }
      }

      .loading-state {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
        color: var(--el-text-color-secondary);

        .loading-icon {
          margin-right: 10px;
          animation: rotate 1.5s linear infinite;
        }
      }
    }

    .dialog-footer {
      display: flex;
      justify-content: space-between;
      padding: 20px 10px 0;
      border-top: 1px solid var(--el-border-color-light);
      margin-top: 20px;

      .el-button {
        min-width: 100px;
      }
    }
  }
}

/* 3D卡片翻转效果 */
.mask-card {
  position: relative;
  height: 320px;
  perspective: 1000px;
  cursor: pointer;
  border-radius: 12px;

  .card-face {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    transition: transform 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-light);

    .card-content {
      padding: 25px;
      height: 100%;
      display: flex;
      flex-direction: column;
    }
  }

  .card-front {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;

    .card-icon {
      margin-bottom: 20px;
      color: var(--el-color-primary);
      transition: transform 0.3s ease;
    }

    .mask-name {
      margin: 0 0 15px;
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    .mask-description {
      margin: 0;
      font-size: 14px;
      color: var(--el-text-color-regular);
      line-height: 1.6;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 4;
      -webkit-box-orient: vertical;
      min-height: 90px;
    }

    .flip-hint {
      margin-top: auto;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      color: var(--el-text-color-secondary);
      opacity: 0.7;

      .el-icon {
        margin-right: 5px;
        font-size: 14px;
        transition: transform 0.5s ease;
      }
    }

    &:hover {
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
      border-color: var(--el-color-primary-light-5);

      .card-icon {
        transform: scale(1.1);
      }

      .flip-hint .el-icon {
        transform: rotate(180deg);
      }
    }
  }

  .card-back {
    transform: rotateY(180deg);
    display: flex;
    flex-direction: column;

    .card-icon-large {
      text-align: center;
      margin-bottom: 20px;
      color: var(--el-color-primary);
    }

    .mask-name {
      text-align: center;
      margin: 0 0 15px;
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    .prompt-container {
      flex: 1;
      display: flex;
      flex-direction: column;

      .prompt-label {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 8px;
        color: var(--el-text-color-secondary);
      }

      .prompt-scrollbar {
        flex: 1;
        border-radius: 8px;
        background: var(--el-fill-color-light);
        padding: 12px;

        .mask-prompt {
          font-size: 14px;
          color: var(--el-text-color-regular);
          line-height: 1.6;
          white-space: pre-line;
        }
      }
    }

    .flip-hint {
      margin-top: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      color: var(--el-text-color-secondary);
      opacity: 0.7;

      .el-icon {
        margin-right: 5px;
        font-size: 14px;
        transition: transform 0.5s ease;
      }
    }

    &:hover {
      .flip-hint .el-icon {
        transform: rotate(180deg);
      }
    }
  }

  /* 翻转效果 */
  &.is-flipped {
    .card-front {
      transform: rotateY(-180deg);
    }

    .card-back {
      transform: rotateY(0deg);
    }
  }
}

/* 增强选中状态的视觉效果 */
.mask-card.is-selected {
  .card-face {
    box-shadow: 0 0 15px rgba(var(--el-color-primary-rgb), 0.3);
    border: 2px solid var(--el-color-primary);
  }

  .selection-badge {
    transform: scale(1.1);
  }
}

/* 添加脉冲动画 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(var(--el-color-primary-rgb), 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(var(--el-color-primary-rgb), 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(var(--el-color-primary-rgb), 0);
  }
}

/* 暗黑模式适配 */
:deep(.el-dialog) {
  background-color: var(--el-bg-color);
  color: var(--el-text-color-primary);

  .el-dialog__header {
    border-bottom: 1px solid var(--el-border-color-light);
  }

  .el-dialog__title {
    color: var(--el-text-color-primary);
  }
}

/* 动画 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(var(--el-color-primary-rgb), 0.7);
  }
  70% {
    transform: scale(1.05);
    box-shadow: 0 0 0 10px rgba(var(--el-color-primary-rgb), 0);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(var(--el-color-primary-rgb), 0);
  }
}

.mask-card.is-flipped {
  animation: pulse 0.5s ease;
}
</style>